package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {
    @Autowired
    ClazzMapper clazzMapper;
    @Autowired
    EmpMapper empMapper;
    @Override
    public PageResult<Clazz> selectAll(String name, int page, int pageSize, LocalDate begin, LocalDate end) {
        IPage<Clazz>iPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null&&name!="",Clazz::getName,name).between(begin!=null&&end!=null,Clazz::getEndDate,begin,end);
        this.page(iPage,queryWrapper);
        List<Clazz> records = iPage.getRecords();
        long total = iPage.getTotal();
        if (CollectionUtils.isEmpty(records)){
            //查询班主任信息
            List<Integer> list = records.stream().map(Clazz::getMasterId).toList();
            List<Integer> ids = list.stream().distinct().toList();
            List<Emp> emps = empMapper.selectByIds(ids);
            records.forEach(clazz->{
               emps.stream().filter(emp ->clazz.getMasterId().equals(emp.getId())).findFirst().ifPresent(emp -> clazz.setMasterName(emp.getName()));
            });

        }

        return new PageResult<>(total,records);
    }
}
